<!DOCTYPE html>
<html lang="zh-cn" color-mode="light">

  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="keywords" content="" />
  <meta name="author" content="郁涛丶" />
  <meta name="description" content="" />
  
  
  <title>
    
      Python__RE模块与正则表达式 
      
      
      |
    
     郁涛丶&#39;s Blog
  </title>

  
    <link rel="apple-touch-icon" href="/images/favicon.png">
    <link rel="icon" href="/images/favicon.png">
  

  <!-- Raleway-Font -->
  <link href="https://fonts.googleapis.com/css?family=Raleway&display=swap" rel="stylesheet">

  <!-- hexo site css -->
  
<link rel="stylesheet" href="/css/color-scheme.css">
<link rel="stylesheet" href="/css/base.css">
<link rel="stylesheet" href="//at.alicdn.com/t/font_1886449_67xjft27j1l.css">
<link rel="stylesheet" href="/css/github-markdown.css">
<link rel="stylesheet" href="/css/highlight.css">
<link rel="stylesheet" href="/css/comments.css">

  <!-- 代码块风格 -->
  
    
<link rel="stylesheet" href="/css/figcaption/mac-block.css">

  

  <!-- jquery3.3.1 -->
  
    <script defer type="text/javascript" src="/plugins/jquery.min.js"></script>
  

  <!-- fancybox -->
  
    <link href="/plugins/jquery.fancybox.min.css" rel="stylesheet">
    <script defer type="text/javascript" src="/plugins/jquery.fancybox.min.js"></script>
  
  
<script src="/js/fancybox.js"></script>


  

  <script>
    var html = document.documentElement
    const colorMode = localStorage.getItem('color-mode')
    if (colorMode) {
      document.documentElement.setAttribute('color-mode', colorMode)
    }
  </script>
<!-- hexo injector head_end start -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.css">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hexo-math@4.0.0/dist/style.css">
<!-- hexo injector head_end end --><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="郁涛丶's Blog" type="application/atom+xml">
</head>


  <body>
    <div id="app">
      <div class="header">
  <div class="avatar">
    <a href="/">
      <!-- 头像取消懒加载，添加no-lazy -->
      
        <img src="/images/avatar.png" alt="">
      
    </a>
    <div class="nickname"><a href="/">Ghostasky</a></div>
  </div>
  <div class="navbar">
    <ul>
      
        <li class="nav-item" data-path="/">
          <a href="/">Home</a>
        </li>
      
        <li class="nav-item" data-path="/archives/">
          <a href="/archives/">Archives</a>
        </li>
      
        <li class="nav-item" data-path="/categories/">
          <a href="/categories/">Categories</a>
        </li>
      
        <li class="nav-item" data-path="/tags/">
          <a href="/tags/">Tags</a>
        </li>
      
        <li class="nav-item" data-path="/about/">
          <a href="/about/">About</a>
        </li>
      
    </ul>
  </div>
</div>


<script src="/js/activeNav.js"></script>



      <div class="flex-container">
        <!-- 文章详情页，展示文章具体内容，url形式：https://yoursite/文章标题/ -->
<!-- 同时为「标签tag」，「朋友friend」，「分类categories」，「关于about」页面的承载页面，具体展示取决于page.type -->


    <!-- LaTex Display -->

  
    <script async type="text/javascript" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js"></script>
  
  <script>
    MathJax = {
      tex: {
        inlineMath: [['$', '$'], ['\\(', '\\)']]
      }
    }
  </script>


        
            
                <!-- clipboard -->

  
    <script async type="text/javascript" src="/plugins/clipboard.min.js"></script>
  
  
<script src="/js/codeCopy.js"></script>



                    
                        
                                
                                        
                                                
                                                        
                                                            <!-- 文章内容页 url形式：https://yoursite/文章标题/ -->
                                                            <div class="container post-details" id="post-details">
                                                                <div class="post-content">
                                                                    <div class="post-title">
                                                                        Python__RE模块与正则表达式
                                                                    </div>
                                                                    <div class="post-attach">
                                                                        <span class="post-pubtime">
        <i class="iconfont icon-updatetime" title="Update time"></i>
        2020-11-21
      </span>

                                                                        <span class="post-pubtime"> 本文共2.6k字 </span>

                                                                        <span class="post-pubtime">
        大约需要13min
      </span>

                                                                        
                                                                                    <span class="post-categories">
        <i class="iconfont icon-bookmark" title="Categories"></i>
        
        <span class="span--category">
          <a href="/categories/Technology/" title="Technology">
            <b>#</b> Technology
          </a>
        </span>
                                                                                    
                                                                                        </span>
                                                                                        
                                                                            <span class="post-tags">
        <i class="iconfont icon-tags" title="Tags"></i>
        
        <span class="span--tag">
          <a href="/tags/Python/" title="Python">
            <b>#</b> Python
          </a>
        </span>
                                                                            
                                                                                </span>
                                                                                
                                                                    </div>
                                                                    <div class="markdown-body">
                                                                        <p>[TOC]</p>
<hr>
<h1 id="一Python模块之RE模块"><a href="#一Python模块之RE模块" class="headerlink" title="一Python模块之RE模块"></a>一Python模块之RE模块</h1><p>一些可选值：</p>
<ul>
<li>re.I（全拼：ignorecase）：忽略大小写</li>
<li>re.M（全拼：multiline）：多行模式，改变^和$的行为</li>
<li>re.S（全拼：datall）：点任意匹配模式，改变.的行为</li>
<li>re.L（全拼locale）：是预定字符串类\w \W \b \B \s \S取决于当前区域设定</li>
<li>re.U（全拼：UNICODE）: 使预定字符类 \w \W \b \B \s \S \d \D 取决于unicode定义的字符属性</li>
<li>re.X（全拼：VERBOSE）: 详细模式。这个模式下正则表达式可以是多行，忽略空白字符，并可以加入注释。</li>
</ul>
<p>方法：</p>
<p>1.group([group1, …]):<br>获得一个或多个分组截获的字符串；指定多个参数时将以元组形式返回。group1可以使用编号也可以使用别名；编号0代表整个匹配的子串；不填写参数时，返回group(0)；没有截获字符串的组返回None；截获了多次的组返回最后一次截获的子串。<br>2.groups([default]):<br>以元组形式返回全部分组截获的字符串。相当于调用group(1,2,…last)。default表示没有截获字符串的组以这个值替代，默认为None。<br>3.groupdict([default]):<br>返回以有别名的组的别名为键、以该组截获的子串为值的字典，没有别名的组不包含在内。default含义同上。<br>4.start([group]):<br>返回指定的组截获的子串在string中的起始索引（子串第一个字符的索引）。group默认值为0。<br>5.end([group]):<br>返回指定的组截获的子串在string中的结束索引（子串最后一个字符的索引+1）。group默认值为0。<br>6.span([group]):<br>返回(start(group), end(group))。<br>7.expand(template):<br>将匹配到的分组代入template中然后返回。template中可以使用\id或\g、\g引用分组，但不能使用编号0。\id与\g是等价的；但\10将被认为是第10个分组，如果你想表达\1之后是字符’0’，只能使用\g0。</p>
<p>pattern可以理解为一个匹配模式，利用re.compile方法就可以。例如:</p>
<p><code>pattern = re.compile(r&#39;hello&#39;)</code></p>
<p>在参数中传入原生字符串对象，通过compile方法生成一个pattern对象。</p>
<h2 id="1-re-match-pattern-string-flags"><a href="#1-re-match-pattern-string-flags" class="headerlink" title="1.re.match(pattern,string,[flags])"></a>1.re.match(pattern,string,[flags])</h2><p>这个方法会从string字符串的开头开始，尝试匹配pattern，一直向后匹配，如遇到无法匹配的字符串，返回None，如果匹配未结束已经到达string尾，也会返回None。另个结果表示匹配失败，否则成功，同时匹配终止。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line">pattern = re.<span class="built_in">compile</span>(<span class="string">r&#x27;hello&#x27;</span>)<span class="comment">#r的意思是&quot;原生字符串&quot;</span></span><br><span class="line"></span><br><span class="line">result_1 = re.match(pattern,<span class="string">&#x27;hello&#x27;</span>)</span><br><span class="line">result_2 = re.match(pattern,<span class="string">&#x27;helloo, ASDF&#x27;</span>)</span><br><span class="line">result_3 = re.match(pattern,<span class="string">&#x27;helo asdf&#x27;</span>)</span><br><span class="line">result_4 = re.match(pattern,<span class="string">&#x27;hello adf&#x27;</span>)</span><br><span class="line"><span class="keyword">if</span> result_1:</span><br><span class="line">    <span class="built_in">print</span> result_1.group()</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="built_in">print</span> <span class="string">&quot;result_1 匹配失败&quot;</span></span><br><span class="line">    </span><br><span class="line"><span class="keyword">if</span> result_2:</span><br><span class="line">    <span class="built_in">print</span> result_2.group()</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="built_in">print</span> <span class="string">&quot;result_2 匹配失败&quot;</span></span><br><span class="line">    </span><br><span class="line"><span class="keyword">if</span> result_3:</span><br><span class="line">    <span class="built_in">print</span> result_3.group()</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="built_in">print</span> <span class="string">&quot;result_3 匹配失败&quot;</span></span><br><span class="line"><span class="keyword">if</span> result_4:</span><br><span class="line">    <span class="built_in">print</span> result_4.group()</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="built_in">print</span> <span class="string">&quot;result_4 匹配失败&quot;</span></span><br></pre></td></tr></table></figure>

<p>结果是只有3未匹配…</p>
<h2 id="2-re-search-pattern-string-flags"><a href="#2-re-search-pattern-string-flags" class="headerlink" title="2.re.search(pattern,string,[flags])"></a>2.re.search(pattern,string,[flags])</h2><p>与match类似，match是从头开始检测，search会扫描整个string</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line">pattern = re.<span class="built_in">compile</span>(<span class="string">r&#x27;hello&#x27;</span>)<span class="comment">#r的意思是&quot;原生字符串&quot;</span></span><br><span class="line"></span><br><span class="line">result_1 = re.match(pattern,<span class="string">&#x27;hello&#x27;</span>)</span><br><span class="line">result_2 = re.match(pattern,<span class="string">&#x27;helloo, ASDF&#x27;</span>)</span><br><span class="line">result_3 = re.match(pattern,<span class="string">&#x27;helo asdf&#x27;</span>)</span><br><span class="line">result_4 = re.match(pattern,<span class="string">&#x27;hello adf&#x27;</span>)</span><br><span class="line"><span class="keyword">if</span> result_1:</span><br><span class="line">    <span class="built_in">print</span> result_1.group()</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="built_in">print</span> <span class="string">&quot;result_1 匹配失败&quot;</span></span><br><span class="line">    </span><br><span class="line"><span class="keyword">if</span> result_2:</span><br><span class="line">    <span class="built_in">print</span> result_2.group()</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="built_in">print</span> <span class="string">&quot;result_2 匹配失败&quot;</span></span><br><span class="line">    </span><br><span class="line"><span class="keyword">if</span> result_3:</span><br><span class="line">    <span class="built_in">print</span> result_3.group()</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="built_in">print</span> <span class="string">&quot;result_3 匹配失败&quot;</span></span><br><span class="line"><span class="keyword">if</span> result_4:</span><br><span class="line">    <span class="built_in">print</span> result_4.group()</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="built_in">print</span> <span class="string">&quot;result_4 匹配失败&quot;</span></span><br></pre></td></tr></table></figure>

<h1 id="3-re-split-pattern-string-flags"><a href="#3-re-split-pattern-string-flags" class="headerlink" title="3.re.split(pattern,string,[flags])"></a>3.re.split(pattern,string,[flags])</h1><p>按照能够匹配的子串将少天日工分割后返回列表。</p>
<p>maxsplit用于指定最大分割次数，不指定将全部分割</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line">pattern = re.<span class="built_in">compile</span>(<span class="string">r&#x27;\d+&#x27;</span>)</span><br><span class="line"><span class="built_in">print</span> re.split(pattern,<span class="string">&#x27;one1two2three3&#x27;</span>)</span><br></pre></td></tr></table></figure>

<h2 id="4-re-findall-pattern-string-flags"><a href="#4-re-findall-pattern-string-flags" class="headerlink" title="4.re.findall(pattern,string,[flags])"></a>4.re.findall(pattern,string,[flags])</h2><p>搜索string，以列表的形式返回全部匹配的子串</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line">pattern = re.<span class="built_in">compile</span>(<span class="string">r&#x27;\d+&#x27;</span>)</span><br><span class="line"><span class="built_in">print</span> re.findall(pattern,<span class="string">&#x27;one1two2three3&#x27;</span>)</span><br></pre></td></tr></table></figure>

<h2 id="5-re-finditer-pattern-string-flags"><a href="#5-re-finditer-pattern-string-flags" class="headerlink" title="5.re.finditer(pattern,string,[flags])"></a>5.re.finditer(pattern,string,[flags])</h2><p>搜索string，返回一个顺序访问没一个匹配结果（match对象）的迭代器</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line">pattern = re.<span class="built_in">compile</span>(<span class="string">r&#x27;\d+&#x27;</span>)</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> re.finditer(pattern,<span class="string">&#x27;one1two2three3four4&#x27;</span>):</span><br><span class="line">    <span class="built_in">print</span> i.group()</span><br></pre></td></tr></table></figure>

<h2 id="6-re-sub-pattern-repl-string-count"><a href="#6-re-sub-pattern-repl-string-count" class="headerlink" title="6.re.sub(pattern,repl,string ,[count])"></a>6.re.sub(pattern,repl,string ,[count])</h2><p>使用repl替换string中没一个匹配的子串返回替换后的字符串</p>
<h2 id="7-re-subn-pattern-repl-string-count"><a href="#7-re-subn-pattern-repl-string-count" class="headerlink" title="7.re.subn(pattern,repl,string,[count])"></a>7.re.subn(pattern,repl,string,[count])</h2><p>返回 (sub(repl, string[, count]), 替换次数)</p>
<h1 id="二、正则表达式"><a href="#二、正则表达式" class="headerlink" title="二、正则表达式"></a>二、正则表达式</h1><p>正则表达式由以下几个部分组成：</p>
<ul>
<li>原子（普通字符，如a~z）</li>
<li>有特殊功能的字符（称为元字符，例如*+？等）</li>
<li>模式修正符</li>
</ul>
<p><code>/&lt;a.*?(?:|\\t|\\r|\\n)?href=[\&#39;&quot;]?(.+?)[\&#39;&quot;]?(?:(?:|\\t|\\r|\\n)+.*?)?&gt;(.+?)&lt;\/a.*?&gt;/sim</code></p>
<p>拆分后如下：</p>
<ul>
<li>定界符使用的是两个斜线’&#x2F;‘</li>
<li>原子用到了&lt;、a、href、&#x3D;、’、”、等普通字符和\t,\r,\n等转义字符</li>
<li>元字符使用了<a href></a>|.*?+d等具有特殊含义的字符</li>
</ul>
<h2 id="1-定界符"><a href="#1-定界符" class="headerlink" title="1.定界符"></a>1.定界符</h2><p>不仅仅局限于斜杠&#x2F;，除了字母、数字、反斜线以外的字符都可以，如#!{}|等</p>
<h2 id="2-原子"><a href="#2-原子" class="headerlink" title="2.原子"></a>2.原子</h2><p>原子是正则表达式最基本的组成单位，这里将其划分为5类进行介绍：</p>
<ol>
<li><p>普通字符作为原子</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">如a~z,0~9,A~Z等</span><br><span class="line">/5/  ---用于匹配是否有5</span><br><span class="line">/php/  ---用于匹配是否有php</span><br></pre></td></tr></table></figure>
</li>
<li><p>一些特殊字符和元字符作为原子</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">使用特殊字符必须转义，如：</span><br><span class="line">/\./    --用于匹配是否由于.出现</span><br><span class="line">/\&lt;br \/&gt;/---用于匹配是否有&lt;br /&gt;出现</span><br></pre></td></tr></table></figure>
</li>
<li><p>一些非打印字符作为原子</p>
<p>非打印字符，如空格，回车，制表符等。</p>
<table>
<thead>
<tr>
<th>原子字符</th>
<th>含义描述</th>
</tr>
</thead>
<tbody><tr>
<td>\cx</td>
<td>匹配一个由x指明的控制字符，例如，\cM匹配一个Ctrl+M或回车符。x的值必须为a<del>z或者A</del>Z之一。否则，将c视为一个原义的d字符</td>
</tr>
<tr>
<td>\f</td>
<td>匹配一个换页符</td>
</tr>
<tr>
<td>\n</td>
<td>匹配一个换行符</td>
</tr>
<tr>
<td>\r</td>
<td>匹配一个回车符</td>
</tr>
<tr>
<td>\t</td>
<td>匹配一个制表符</td>
</tr>
<tr>
<td>\v</td>
<td>匹配一个垂直制表符</td>
</tr>
</tbody></table>
</li>
<li><p>使用“通用字符类型”作为原子</p>
<p>前面介绍 的不管是打印字符还是非打印字符，都是一个原子只能匹配一个字符。有时需要匹配所有字母或者所有数字，这是就要用“通用字符类型”</p>
<table>
<thead>
<tr>
<th>原子字符</th>
<th>含义描述</th>
</tr>
</thead>
<tbody><tr>
<td>\d</td>
<td>匹配任意一个十进制数字，等价于[0~9]</td>
</tr>
<tr>
<td>\D</td>
<td>匹配任意一个非十进制数字，等价于[ ^ 0~9 ]</td>
</tr>
<tr>
<td>\s</td>
<td>匹配任意一个空白字符</td>
</tr>
<tr>
<td>\S</td>
<td>匹配出空白字符以外的任何一个字符</td>
</tr>
<tr>
<td>\w</td>
<td>匹配任意一个数字、字母、或下划线</td>
</tr>
<tr>
<td>\W</td>
<td>匹配除数字、字母、或下划线以外的任何一个字符</td>
</tr>
</tbody></table>
</li>
<li><p>自定义原子表[]作为原子</p>
<p>直接上例子：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">/[apj]sp/   ---可以匹配asp jsp或psp三种，从原子表中仅选一种作为原子</span><br><span class="line">/[^apj]sp   ---可以匹配除asp jsp 和PSP之外的字符串，如xsp，zsp等</span><br><span class="line">/0[xX][0-9a-fA-F]  ---可以匹配一个简单的十六进制数</span><br></pre></td></tr></table></figure></li>
</ol>
<h1 id="3-元字符"><a href="#3-元字符" class="headerlink" title="3.元字符"></a>3.元字符</h1><table>
<thead>
<tr>
<th>元字符</th>
<th>含义描述</th>
</tr>
</thead>
<tbody><tr>
<td>*</td>
<td>匹配0次1次或多次其前的原子</td>
</tr>
<tr>
<td>+</td>
<td>匹配1次或多次其前的原子</td>
</tr>
<tr>
<td>?</td>
<td>匹配0次或1次其前的原子</td>
</tr>
<tr>
<td>|</td>
<td>匹配两个或多个分支选择</td>
</tr>
<tr>
<td>.</td>
<td>匹配除了换行符之外的任意一个字符</td>
</tr>
<tr>
<td>{n}</td>
<td>表示其前面的原子恰好出现n次</td>
</tr>
<tr>
<td>{n,}</td>
<td>表示其前面的原子出现不少于n次</td>
</tr>
<tr>
<td>{n,m}</td>
<td>其前面的原子出现次数介于n和m之间</td>
</tr>
<tr>
<td>^或\A</td>
<td>匹配输入字符串的开始位置</td>
</tr>
<tr>
<td>$或\Z</td>
<td>匹配输入字符串的结束为止</td>
</tr>
<tr>
<td>\b</td>
<td>匹配单词的边界</td>
</tr>
<tr>
<td>\B</td>
<td>匹配除单词边界以外的部分</td>
</tr>
<tr>
<td>[]</td>
<td>匹配方括号中指定的任意一个原子</td>
</tr>
<tr>
<td>[^]</td>
<td>匹配除方括号中指定的任意一个原子</td>
</tr>
<tr>
<td>()</td>
<td>匹配器整体为一个原子，即模式单元可以理解为多个原子组成的大原子</td>
</tr>
</tbody></table>
<p>栗子如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">/a\s*b/        --可以匹配在a和b之间没用空白，一个空白或多个空白的情况</span><br><span class="line">/a\d+b/		----可以匹配在a和b之间1个数字或多个数字的情况</span><br><span class="line">/a\W?b/		----可以匹配在a和b之间有一个货没有特殊字符的情况</span><br><span class="line">/ax&#123;4&#125;b/		----可以匹配在a和b之间必须有4个x，如axxxxb</span><br><span class="line">/ax&#123;2,&#125;b/      ----ab之间至少两个x</span><br><span class="line">/ax&#123;2,4&#125;b/		--ab之间的x的个数在2,4之间</span><br><span class="line"></span><br><span class="line">/^this/   --匹配此字符串是否是以this开始的</span><br><span class="line">/this$/</span><br><span class="line">/\bis\b/ ---匹配此字符串中是否含有is</span><br><span class="line">/\Bis\b/  ----查找字符串is时，左边不能有边界，右边必须有边界，如this</span><br><span class="line">/a.b/  </span><br><span class="line">/Linux|Apache|mysql/</span><br><span class="line">/(very)*good/ ---可以匹配good,very good,very very good ....等</span><br><span class="line">/(Windows)(Linus)\\2OS/  ---使用\2再次引用第二个缓冲区中的字符串Linux</span><br><span class="line">/(?:windows)(linux)\\1OS/ ---使用?:忽略了第一个表达式的存储，所以\1引用的就是Linux</span><br></pre></td></tr></table></figure>

<h2 id="模式匹配的优先级："><a href="#模式匹配的优先级：" class="headerlink" title="模式匹配的优先级："></a>模式匹配的优先级：</h2><table>
<thead>
<tr>
<th>元字符</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>\</td>
<td>转义符号</td>
</tr>
<tr>
<td>()、(?: )、(?&#x3D;)、[]</td>
<td>模式单元和原子表</td>
</tr>
<tr>
<td>*、+、?、{n}、{n,}、{n,m}</td>
<td>重复匹配</td>
</tr>
<tr>
<td>^、$、\b、\B、\A、\Z</td>
<td>边界限制</td>
</tr>
<tr>
<td>|</td>
<td>模式选择</td>
</tr>
</tbody></table>
<h3 id="模式修正符"><a href="#模式修正符" class="headerlink" title="模式修正符"></a>模式修正符</h3><p>模式修正符是在正则表达式定界符之外使用</p>
<table>
<thead>
<tr>
<th>模式修正符</th>
<th>功能描述</th>
</tr>
</thead>
<tbody><tr>
<td>i</td>
<td>在和模式进行匹配是不区分大小写</td>
</tr>
<tr>
<td>m</td>
<td>将字符串视为多行。默认的正则开始^和结束$竟目标字符串作为单一的一行字符（甚至其中包含有换行符也是如此）。如果在修正符中加上m，那么开始和结束将会指字符串的每一行，每一行的开头是^，结束是$</td>
</tr>
<tr>
<td>s</td>
<td>如果设定了次修正符，则模式中的圆点字符.匹配所有字符，包括换行符。即将字符串视为单行，换行符作为普通字符看待</td>
</tr>
<tr>
<td>x</td>
<td>模式中的空白忽略不计，除非它已经被转义</td>
</tr>
<tr>
<td>e</td>
<td>只用在preg_replace()函数中，在替换字符串中对逆向引用做正常的替换，将其作为PHP代码求值，并用其结果来替换所搜索的字符串</td>
</tr>
<tr>
<td>U</td>
<td>本修正符反转了匹配数量的值使其不是默认的重复，而变成在后面跟上?才变得重复</td>
</tr>
<tr>
<td>D</td>
<td>模式中的美元字符仅匹配字符串的结尾。没有此选项是，如果最后一个字符是换行符，则美元符号也会匹配此字符之前的内容。如果设定了m修正符，则忽略此选项。</td>
</tr>
</tbody></table>

                                                                    </div>
                                                                    
                                                                        <div class="prev-or-next">
                                                                            <div class="post-foot-next">
                                                                                
                                                                                    <a href="/2020/11/19/SQL%E6%B3%A8%E5%85%A5%E5%B0%8F%E7%BB%93/" target="_self">
                                                                                        <i class="iconfont icon-chevronleft"></i>
                                                                                        <span>Prev</span>
                                                                                    </a>
                                                                                    
                                                                            </div>
                                                                            <div class="post-attach">
                                                                                <!-- <span class="post-pubtime">
              <i class="iconfont icon-updatetime" title="Update time"></i>
              2020-11-21
            </span> -->

                                                                                
                                                                                            <span class="post-categories">
          <!-- <i class="iconfont icon-bookmark" title="Categories"></i> -->
          
          <!-- <span class="span--category">
            <a href="/categories/Technology/" title="Technology">
              <b>#</b> Technology
            </a>
          </span> -->
                                                                                            
                                                                                                </span>
                                                                                                
                                                                                    <span class="post-tags">
          <!-- <i class="iconfont icon-tags" title="Tags"></i> -->
          
          <!-- <span class="span--tag">
            <a href="/tags/Python/" title="Python">
              <b>#</b> Python
            </a>
          </span> -->
                                                                                    
                                                                                        </span>
                                                                                        
                                                                            </div>
                                                                            <div class="post-foot-prev">
                                                                                
                                                                                    <a href="/2020/11/22/BUU-RE-1/" target="_self">
                                                                                        <span>Next</span>
                                                                                        <i class="iconfont icon-chevronright"></i>
                                                                                    </a>
                                                                                    
                                                                            </div>
                                                                        </div>
                                                                        
                                                                </div>
                                                                
  <div id="btn-catalog" class="btn-catalog">
    <i class="iconfont icon-catalog"></i>
  </div>
  <div class="post-catalog hidden" id="catalog">
    <div class="title">Contents</div>
    <div class="catalog-content">
      
        <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%80Python%E6%A8%A1%E5%9D%97%E4%B9%8BRE%E6%A8%A1%E5%9D%97"><span class="toc-text">一Python模块之RE模块</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-re-match-pattern-string-flags"><span class="toc-text">1.re.match(pattern,string,[flags])</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-re-search-pattern-string-flags"><span class="toc-text">2.re.search(pattern,string,[flags])</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#3-re-split-pattern-string-flags"><span class="toc-text">3.re.split(pattern,string,[flags])</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#4-re-findall-pattern-string-flags"><span class="toc-text">4.re.findall(pattern,string,[flags])</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-re-finditer-pattern-string-flags"><span class="toc-text">5.re.finditer(pattern,string,[flags])</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-re-sub-pattern-repl-string-count"><span class="toc-text">6.re.sub(pattern,repl,string ,[count])</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7-re-subn-pattern-repl-string-count"><span class="toc-text">7.re.subn(pattern,repl,string,[count])</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%8C%E3%80%81%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F"><span class="toc-text">二、正则表达式</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E5%AE%9A%E7%95%8C%E7%AC%A6"><span class="toc-text">1.定界符</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E5%8E%9F%E5%AD%90"><span class="toc-text">2.原子</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#3-%E5%85%83%E5%AD%97%E7%AC%A6"><span class="toc-text">3.元字符</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A8%A1%E5%BC%8F%E5%8C%B9%E9%85%8D%E7%9A%84%E4%BC%98%E5%85%88%E7%BA%A7%EF%BC%9A"><span class="toc-text">模式匹配的优先级：</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%BC%8F%E4%BF%AE%E6%AD%A3%E7%AC%A6"><span class="toc-text">模式修正符</span></a></li></ol></li></ol></li></ol>
      
    </div>
  </div>

  
<script src="/js/catalog.js"></script>




                                                                    
                                                                        <div class="comments-container">
                                                                            







                                                                        </div>
                                                                        
                                                            </div>
                                                            
        
<div class="footer">
  <div class="social">
    <ul>
      
        <li>
          <a title="github" target="_blank" rel="noopener" href="https://github.com/Ghostasky">
            <i class="iconfont icon-github"></i>
          </a>
        </li>
      
        <li>
          <a title="twitter" target="_blank" rel="noopener" href="https://twitter.com/ghostasky">
            <i class="iconfont icon-twitter"></i>
          </a>
        </li>
      
    </ul>
  </div>
  
    
    <div class="footer-more">
      
        <a target="_blank" rel="noopener" href="https://github.com/Ghostasky">怕什么真理无穷，进一寸有进一寸的欢喜。</a>
        
    </div>
  
    
    <div class="footer-more">
      
        <a target="_blank" rel="noopener" href="https://github.com/zchengsite/hexo-theme-oranges">Copyright © 2022 Oranges</a>
        
    </div>
  
    
    <div class="footer-more">
      
        <a target="_blank" rel="noopener" href="https://github.com/zchengsite/hexo-theme-oranges">Theme by Oranges | Powered by Hexo</a>
        
    </div>
  
</div>

      </div>

      <div class="tools-bar">
        <div class="back-to-top tools-bar-item hidden">
  <a href="javascript: void(0)">
    <i class="iconfont icon-chevronup"></i>
  </a>
</div>


<script src="/js/backtotop.js"></script>



        
  <div class="search-icon tools-bar-item" id="search-icon">
    <a href="javascript: void(0)">
      <i class="iconfont icon-search"></i>
    </a>
  </div>

  <div class="search-overlay hidden">
    <div class="search-content" tabindex="0">
      <div class="search-title">
        <span class="search-icon-input">
          <a href="javascript: void(0)">
            <i class="iconfont icon-search"></i>
          </a>
        </span>
        
          <input type="text" class="search-input" id="search-input" placeholder="Search...">
        
        <span class="search-close-icon" id="search-close-icon">
          <a href="javascript: void(0)">
            <i class="iconfont icon-close"></i>
          </a>
        </span>
      </div>
      <div class="search-result" id="search-result"></div>
    </div>
  </div>

  <script type="text/javascript">
    var inputArea = document.querySelector("#search-input")
    var searchOverlayArea = document.querySelector(".search-overlay")

    inputArea.onclick = function() {
      getSearchFile()
      this.onclick = null
    }

    inputArea.onkeydown = function() {
      if(event.keyCode == 13)
        return false
    }

    function openOrHideSearchContent() {
      let isHidden = searchOverlayArea.classList.contains('hidden')
      if (isHidden) {
        searchOverlayArea.classList.remove('hidden')
        document.body.classList.add('hidden')
        // inputArea.focus()
      } else {
        searchOverlayArea.classList.add('hidden')
        document.body.classList.remove('hidden')
      }
    }

    function blurSearchContent(e) {
      if (e.target === searchOverlayArea) {
        openOrHideSearchContent()
      }
    }

    document.querySelector("#search-icon").addEventListener("click", openOrHideSearchContent, false)
    document.querySelector("#search-close-icon").addEventListener("click", openOrHideSearchContent, false)
    searchOverlayArea.addEventListener("click", blurSearchContent, false)

    var searchFunc = function (path, search_id, content_id) {
      'use strict';
      var $input = document.getElementById(search_id);
      var $resultContent = document.getElementById(content_id);
      $resultContent.innerHTML = "<ul><span class='local-search-empty'>First search, index file loading, please wait...<span></ul>";
      $.ajax({
        // 0x01. load xml file
        url: path,
        dataType: "xml",
        success: function (xmlResponse) {
          // 0x02. parse xml file
          var datas = $("entry", xmlResponse).map(function () {
            return {
              title: $("title", this).text(),
              content: $("content", this).text(),
              url: $("url", this).text()
            };
          }).get();
          $resultContent.innerHTML = "";

          $input.addEventListener('input', function () {
            // 0x03. parse query to keywords list
            var str = '<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length <= 0) {
              return;
            }
            // 0x04. perform local searching
            datas.forEach(function (data) {
              var isMatch = true;
              var content_index = [];
              if (!data.title || data.title.trim() === '') {
                data.title = "Untitled";
              }
              var orig_data_title = data.title.trim();
              var data_title = orig_data_title.toLowerCase();
              var orig_data_content = data.content.trim().replace(/<[^>]+>/g, "");
              var data_content = orig_data_content.toLowerCase();
              var data_url = data.url;
              var index_title = -1;
              var index_content = -1;
              var first_occur = -1;
              // only match artiles with not empty contents
              if (data_content !== '') {
                keywords.forEach(function (keyword, i) {
                  index_title = data_title.indexOf(keyword);
                  index_content = data_content.indexOf(keyword);

                  if (index_title < 0 && index_content < 0) {
                    isMatch = false;
                  } else {
                    if (index_content < 0) {
                      index_content = 0;
                    }
                    if (i == 0) {
                      first_occur = index_content;
                    }
                    // content_index.push({index_content:index_content, keyword_len:keyword_len});
                  }
                });
              } else {
                isMatch = false;
              }
              // 0x05. show search results
              if (isMatch) {
                str += "<li><a href='" + data_url + "' class='search-result-title'>" + orig_data_title + "</a>";
                var content = orig_data_content;
                if (first_occur >= 0) {
                  // cut out 100 characters
                  var start = first_occur - 20;
                  var end = first_occur + 80;

                  if (start < 0) {
                    start = 0;
                  }

                  if (start == 0) {
                    end = 100;
                  }

                  if (end > content.length) {
                    end = content.length;
                  }

                  var match_content = content.substr(start, end);

                  // highlight all keywords
                  keywords.forEach(function (keyword) {
                    var regS = new RegExp(keyword, "gi");
                    match_content = match_content.replace(regS, "<span class=\"search-keyword\">" + keyword + "</span>");
                  });

                  str += "<p class=\"search-result-abstract\">" + match_content + "...</p>"
                }
                str += "</li>";
              }
            });
            str += "</ul>";
            if (str.indexOf('<li>') === -1) {
              return $resultContent.innerHTML = "<ul><span class='local-search-empty'>No result<span></ul>";
            }
            $resultContent.innerHTML = str;
          });
        },
        error: function(xhr, status, error) {
          $resultContent.innerHTML = ""
          if (xhr.status === 404) {
            $resultContent.innerHTML = "<ul><span class='local-search-empty'>The search.xml file was not found, please refer to：<a href='https://github.com/zchengsite/hexo-theme-oranges#configuration' target='_black'>configuration</a><span></ul>";
          } else {
            $resultContent.innerHTML = "<ul><span class='local-search-empty'>The request failed, Try to refresh the page or try again later.<span></ul>";
          }
        }
      });
      $(document).on('click', '#search-close-icon', function() {
        $('#search-input').val('');
        $('#search-result').html('');
      });
    }

    var getSearchFile = function() {
        var path = "/search.xml";
        searchFunc(path, 'search-input', 'search-result');
    }
  </script>




        
  <div class="tools-bar-item theme-icon" id="switch-color-scheme">
    <a href="javascript: void(0)">
      <i id="theme-icon" class="iconfont icon-moon"></i>
    </a>
  </div>

  
<script src="/js/colorscheme.js"></script>





        
  
    <div class="share-icon tools-bar-item">
      <a href="javascript: void(0)" id="share-icon">
        <i class="iconfont iconshare"></i>
      </a>
      <div class="share-content hidden">
        
          <a class="share-item" href="https://twitter.com/intent/tweet?text=' + Python__RE%E6%A8%A1%E5%9D%97%E4%B8%8E%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F + '&url=' + https%3A%2F%2Fghostasky.github.io%2F2020%2F11%2F21%2Fpython__re%25E6%25A8%25A1%25E5%259D%2597%25E4%25B8%258E%25E6%25AD%25A3%25E5%2588%2599%25E8%25A1%25A8%25E8%25BE%25BE%25E5%25BC%258F%2F + '" target="_blank" title="Twitter">
            <i class="iconfont icon-twitter"></i>
          </a>
        
        
          <a class="share-item" href="https://www.facebook.com/sharer.php?u=https://ghostasky.github.io/2020/11/21/python__re%E6%A8%A1%E5%9D%97%E4%B8%8E%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/" target="_blank" title="Facebook">
            <i class="iconfont icon-facebooksquare"></i>
          </a>
        
      </div>
    </div>
  
  
<script src="/js/shares.js"></script>



      </div>
    </div>
  </body>
</html>
